package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.ExcelUtil2Element;
import com.ruoyi.system.util.WorkbookExportUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 育苗计划 信息操作处理
 *
 * @author ruoyi
 * @date 2019-07-31
 */
@Controller
@RequestMapping("/system/ncPlan")
public class NcPlanController extends BaseController {
    private String prefix = "system/ncPlan";

    @Autowired
    private INcPlanService ncPlanService;
    @Autowired
    private INcStandardService standardService;


    @Autowired
    private INcCaiService caiService;

    @Autowired
    private INcWorkMirrorService workMirrorService;

    @Autowired
    private INcStageMirrorService stageMirrorService;

    @Autowired
    private ISysDeptService deptService;


    @RequiresPermissions("system:ncPlan:view")
    @GetMapping()
    public String ncPlan() {
        return prefix + "/ncPlan";
    }

    @RequiresPermissions("system:ncPlan:view")
    @GetMapping("/ncPlanFront")
    public String ncPlanFront() {
        return prefix + "/ncPlanFront";
    }

    @RequiresPermissions("system:ncPlan:view")
    @GetMapping("/ncPlanCaiId")
    public String ncPlan(long caiId, ModelMap mmap) {
        mmap.put("ancestors", caiId);

        return prefix + "/ncPlanCaiId";
    }


    @GetMapping("allPlan")
    public String allPlan() {
        return prefix + "/ncPlan-all";
    }

    @RequiresPermissions("system:ncPlan:add")
    @GetMapping("input")
    public String input() {
        return prefix + "/ncPlan-input";
    }

    /**
     * 查询育苗计划列表
     */
    @RequiresPermissions("system:ncPlan:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcPlan ncPlan) {
        startPage();
        List<NcPlan> list = ncPlanService.selectNcPlanList(ncPlan);
        return getDataTable(list);
    }


    /**
     * 新增育苗计划
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存育苗计划
     */
    @RequiresPermissions("system:ncPlan:add")
    @Log(title = "育苗计划", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(NcPlan ncPlan) {
        ncPlan.setStatus("1");
        ncPlan.setPlanCode(NcUtils.getPlanCode());
        ncPlan.setCreateTime(new Date());
        ncPlan.setCreateBy(ShiroUtils.getLoginName());
        ncPlan = ncPlanService.fillValues(ncPlan);
        if (ncPlan == null) {
            return AjaxResult.error("未找到此品种");
        }
        return toAjax(ncPlanService.insertNcPlan(ncPlan));
    }

    /**
     * 修改育苗计划
     */
    @GetMapping("/edit/{planId}")
    public String edit(@PathVariable("planId") Long planId, ModelMap mmap) {
        NcPlan ncPlan = ncPlanService.selectNcPlanById(planId);
        mmap.put("ncPlan", ncPlan);
        return prefix + "/edit";
    }

    /**
     * 修改标准所匹配的计划
     */
    @GetMapping("/editStandard/{planId}")
    public String editStandard(@PathVariable("planId") Long planId, ModelMap mmap) {

        //校验
        NcPlan plan1 = ncPlanService.selectNcPlanById(planId);
        NcStandard st = new NcStandard();
        st.setCropVarieties(plan1.getCropVarieties());
        st.setStandardType("" + plan1.getPlanType());
        st.setStatus("1");
        List<NcStandard> standards = standardService.selectNcStandardList(st);

        for (NcStandard s : standards) {
            if (s.getStandardId() == plan1.getStandardId()) {
                s.setFlag(true);
                break;
            }
        }
        mmap.put("standards", standards);
        mmap.put("planId", planId);
        mmap.put("ncPlan", plan1);

        return prefix + "/edit-plan-standard";
    }

    /**
     * 修改标准所匹配的计划
     */
    @RequiresPermissions("system:ncPlan:edit")
    @Log(title = "修改标准所匹配的计划", businessType = BusinessType.UPDATE)
    @PostMapping("/editStandard")
    @ResponseBody
    public AjaxResult editStandardSave(NcPlan ncPlan) {
        //如果蔬菜品种有变化 则重新 赋值
        ncPlan.setStatus(null);
        if (ncPlan.getStandardId() != null && ncPlan.getStandardId() > 0) {
            ncPlan.setHasStandard("1");
        }
        return toAjax(ncPlanService.updateNcPlan(ncPlan));
    }

    /**
     * 修改保存育苗计划
     */
    @RequiresPermissions("system:ncPlan:edit")
    @Log(title = "育苗计划", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcPlan ncPlan) {
        //如果蔬菜品种有变化 则重新 赋值
        NcPlan ncPlanOld = ncPlanService.selectNcPlanById(ncPlan.getPlanId());
        if (ncPlanOld != null && ncPlanOld.getCropVarieties() == ncPlan.getCropVarieties()) {
            return toAjax(ncPlanService.updateNcPlan(ncPlan));
        } else {
            ncPlan = ncPlanService.fillValues(ncPlan);
            if (ncPlan == null) {
                return AjaxResult.error("未找到此品种");
            }
            return toAjax(ncPlanService.updateNcPlan(ncPlan));
        }

    }

    /**
     * 删除育苗计划
     */
    @RequiresPermissions("system:ncPlan:remove")
    @Log(title = "育苗计划", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncPlanService.deleteNcPlanByIds(ids));
    }

    /**
     * 确认生成育苗计划单
     */
    @Log(title = "确认生成育苗计划单", businessType = BusinessType.DELETE)
    @PostMapping("/confirmTable")
    @ResponseBody
    public AjaxResult confirmTable(String ids) {
        SysUser user = ShiroUtils.getSysUser();
        //TODO 生成育苗计划单
        return toAjax(ncPlanService.createNcPlanByIds(ids, user, Constants.ORDER_YUMIAO));
    }

    /**
     * 计划树图
     *
     * @param plan
     * @param beginTime
     * @param endTime
     * @param mmap
     * @return
     */
    @GetMapping("/showPlan")
    public String showPlan(NcPlan plan, String beginTime, String endTime, ModelMap mmap) {
        if (StringUtils.isNotEmpty(beginTime)) {
            plan.getParams().put("beginTime", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            plan.getParams().put("endTime", endTime);
        }
        //按时间查询育苗计划数量```
        /*状态 1:待生成订单 2：待执行 3.在执行 4.已完成*/
        Map statusCount = ncPlanService.getStatusCount(plan);

        mmap.put("beginTime", beginTime);
        mmap.put("statusCount", statusCount);
        mmap.put("endTime", endTime);
        mmap.put("caiClass", ncPlanService.getBigCaiClass(new NcPlan()));
//        return prefix + "/plan";
        return prefix + "/newGiantMountain";

    }


    @GetMapping("/frontPlanList")
    public String frontPlanList(String status, String beginTime, String endTime, String ancestors, ModelMap mmap) {
        mmap.put("status", status);
        mmap.put("ancestors", ancestors);
        mmap.put("beginTime", beginTime);
        mmap.put("endTime", endTime);
        return prefix + "/ncPlanFront";
    }


    /*计划详情*/
    @GetMapping("/planDetail")
    public String planDetail(Long planId, String planType, ModelMap mmap) {
        ncPlanService.planDetail(planId, planType, mmap);
        return prefix + "/planDetail1";
    }

    /*阶段 或者 工作 详情*/
    @GetMapping("/detail")
    public String detail(Integer type, Long id, String workDate, ModelMap mmap) {
        //1 :工作详情（镜像） 2：阶段详情（镜像）
        if (type == 2) {
            NcStageMirror stage = stageMirrorService.selectNcStageMirrorById(id);
            mmap.put("stage", stage);
            return prefix + "/detail-stage";
        } else if (type == 1) {
            NcWorkMirror work = workMirrorService.selectNcWorkMirrorById(id);
            mmap.put("work", work);
            mmap.put("workDate", workDate);
            return prefix + "/detail-work";
        } else {
            return "main";
        }

    }


    /**
     * 下载导入模板
     *
     * @return
     */
    @RequiresPermissions("system:ncPlan:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {


        WorkbookExportUtil wu = new WorkbookExportUtil(new XSSFWorkbook(), "育苗计划数据导入模板");

        /*订单模板*/
        ExcelUtil2Element<NcPlanTemplate1> m_order = new ExcelUtil2Element<>(NcPlanTemplate1.class, wu);
        m_order.importTemplateExcel("育苗计划数据");


        /*菜分类基础数据*/
        List<NcCai> cais = caiService.selectCaiListHasParent2(new NcCai());
        //过滤鸡蛋牛奶与菜单类
        cais.removeIf(cai -> cai.getAncestors().contains("210") | cai.getAncestors().split(",").length != 3);


        ExcelUtil2Element<NcCai> m_cai = new ExcelUtil2Element<>(NcCai.class, wu);
        m_cai.exportExcel(cais, "菜分类基础数据");


        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        sysDepts.removeIf(dept -> dept.getType() != 2 || dept.getAncestors().split(",").length != 3);
        ExcelUtil2Element<SysDept> m_dept = new ExcelUtil2Element<>(SysDept.class, wu);
        m_dept.exportExcel(sysDepts, "班组基础数据");


        return wu.exportExcel();

    }

    @RequiresPermissions("system:ncPlan:import")
    @Log(title = "计划管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData1(MultipartFile file, boolean updateSupport) throws Exception {
        SysUser sysUser = ShiroUtils.getSysUser();
        AjaxResult messsage = ncPlanService.importNcPlan(sysUser, 1, file, updateSupport);
        return messsage;
    }


    /**
     * 导出育苗计划列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcPlan ncPlan) {

        WorkbookExportUtil wu = new WorkbookExportUtil(new XSSFWorkbook(), "育苗计划数据");


        List<NcPlanExprot1> planList = ncPlanService.selectNcPlanExprot1(ncPlan);
        ExcelUtil2Element<NcPlanExprot1> m_planList = new ExcelUtil2Element<>(NcPlanExprot1.class, wu);
        m_planList.exportExcel(planList, "育苗计划数据");


        NcStandard standard = new NcStandard();
        standard.setStandardType("1");
        List<NcStandard> standardList = standardService.selectNcStandardList(standard);
        ExcelUtil2Element<NcStandard> m_standard = new ExcelUtil2Element<>(NcStandard.class, wu);
        m_standard.exportExcel(standardList, "育苗标准数据");





        /*菜分类基础数据*/
        List<NcCai> cais = caiService.selectCaiListHasParent2(new NcCai());
        //过滤鸡蛋牛奶与菜单类
        cais.removeIf(cai -> cai.getAncestors().contains("210") | cai.getAncestors().split(",").length != 3);
        ExcelUtil2Element<NcCai> m_cai = new ExcelUtil2Element<>(NcCai.class, wu);
        m_cai.exportExcel(cais, "菜分类基础数据");


        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        sysDepts.removeIf(dept -> dept.getType() != 2 || dept.getAncestors().split(",").length != 3);
        ExcelUtil2Element<SysDept> m_dept = new ExcelUtil2Element<>(SysDept.class, wu);
        m_dept.exportExcel(sysDepts, "班组基础数据");

        return wu.exportExcel();
    }



}
